You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

96 lines
2.4 KiB

import { dbGlobal } from "drizzle-pkg/lib/db";
import { users } from "drizzle-pkg/lib/schema/auth";
import { eq } from "drizzle-orm";
import log4js from "logger";
import { requireAdmin } from "#server/utils/admin-guard";
const logger = log4js.getLogger("USERS");
export default defineWrappedResponseHandler(async (event) => {
const id = Number(event.context.params?.id);
const body = await readBody(event);
requireAdmin(event);
if (!id || isNaN(id)) {
throw createError({
statusCode: 400,
statusMessage: "无效的用户ID",
});
}
// Validate email format if provided
if (body.email !== undefined && body.email !== "" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(body.email)) {
throw createError({
statusCode: 400,
statusMessage: "邮箱格式不正确",
});
}
// Validate role
if (body.role && !["admin", "user"].includes(body.role)) {
throw createError({
statusCode: 400,
statusMessage: "无效的角色",
});
}
// Validate status
if (body.status && !["active", "disabled"].includes(body.status)) {
throw createError({
statusCode: 400,
statusMessage: "无效的状态",
});
}
// Check user exists
const [existing] = await dbGlobal
.select({ id: users.id })
.from(users)
.where(eq(users.id, id));
if (!existing) {
throw createError({
statusCode: 404,
statusMessage: "用户不存在",
});
}
// Build update data
const updateData: Partial<{
nickname: string | null;
email: string | null;
role: "admin" | "user";
status: "active" | "disabled";
}> = {};
if (body.nickname !== undefined) updateData.nickname = body.nickname || null;
if (body.email !== undefined) updateData.email = body.email || null;
if (body.role !== undefined) updateData.role = body.role;
if (body.status !== undefined) updateData.status = body.status;
// Perform update
const [updated] = await dbGlobal
.update(users)
.set(updateData)
.where(eq(users.id, id))
.returning({
id: users.id,
username: users.username,
email: users.email,
nickname: users.nickname,
avatar: users.avatar,
role: users.role,
status: users.status,
createdAt: users.createdAt,
});
if (!updated) {
throw createError({
statusCode: 404,
statusMessage: "用户更新失败",
});
}
logger.info("user updated by admin: %s (id: %d)", updated.username, id);
return R.success(updated);
});